package com.example.demo.controller;

import cn.hutool.extra.servlet.JakartaServletUtil;
import com.example.demo.model.core.R;
import com.example.demo.model.form.FileInfoForm;
import com.example.demo.service.SysAttachService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/v1/file")
@Tag(name = "文件管理")
public class SysFileController
{

    @Autowired
    private SysAttachService sysAttachService;

    @PostMapping("/upload")
    @Operation(summary = "文件上传")
    public R<FileInfoForm> uploadFile(
            @Parameter(name = "file", description = "表单文件对象", required = true, in = ParameterIn.DEFAULT, schema = @Schema(name = "file", format = "binary"))
            @RequestPart(value = "file")
            MultipartFile file) {
        FileInfoForm fileInfoForm = sysAttachService.uploadFile(file);
        return R.ok(fileInfoForm);
    }

    @PostMapping("/delete")
    @Operation(summary = "文件删除")
    @SneakyThrows
    public R<Void> deleteFile(@Parameter(description = "附件标识")
    @RequestParam
    String attachGuid) {
        sysAttachService.deleteFile(attachGuid);
        return R.ok();
    }

    @GetMapping("/download")
    @Operation(summary = "文件下载")
    public void downloadFile(@Parameter(name = "attachGuid", description = "附件标识", required = true)
    String attachGuid, HttpServletRequest request, HttpServletResponse response) {
        JakartaServletUtil.write(response, sysAttachService.downloadFile(attachGuid));
    }
}
